/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    InspectRecordLayout, InternalItemProps, OriginalViewProps, useInputControlSure, useItemInputControl,
} from "../../common/base";
import {assertNamesUnique, createItem, EditorAreaConfig,} from "../../common/eHelper";
import {useRecordListSubX} from "../../hook/useRecordListSub";
import {EditStorageContext} from "../../StorageContext";
import {
    BlobInputList, Button, InputLine, Text, TextArea, useToast
} from "customize-easy-ui-component";
import {useMedia} from "use-media";
import {useMeasureInpFilter} from "../../common/hooks";
import {useUppyUpload} from "../../hook/useUppyUpload";
import {TestMethod} from "../../cm/radio/editor";

export const OriginalView=
    React.forwardRef((
        { action: modAction,  verId, repId='', inp, rep}:OriginalViewProps, ref
    ) => {
      const {storage, setStorage} =React.useContext(EditStorageContext) as any;
      const { _ENDOSCOPIC_EX: SubRepIds }=storage;
      if(undefined===SubRepIds)
         return <div>请先确定网络和服务器是正常的。然后才考虑是否要做：
                      <Button intent='danger' onPress={() => setStorage({...storage, _ENDOSCOPIC_EX: [] }) }>
                      还没有数据！立刻初始化</Button></div>;
      return <OriginalViewInner ref={ref} action={modAction} verId={verId} repId={repId} rep={rep}/>
} );

const OriginalViewInner=
    React.forwardRef((
        { action: modAction,  verId, repId='', rep}:OriginalViewProps, ref
    ) => {
        const titleRender = (store: any) => {
            const firstTag=store?.部件;
            return <> { `[${firstTag}] `} </>;
        }
      const {list}=useRecordListSubX(ref,rep,repId,recordPrintList,modAction,verId,'ENDOSCOPIC_EX',titleRender);
      return <React.Fragment>
        {list}
      </React.Fragment>;
} );

export const config测量仪 = [
    [['部件名称', '部件'], ['工作介质', '介质', ] ],
    [['内窥镜型号', '窥镜型'],  ['内窥镜编号', '窥镜编'],  ['入镜深度', {n:'入镜深',u:'mm'}] ],
];

const 示图说明选: string[] | undefined=[ ];
const itemA测点位置=['示图说明','_FILE_部位','检测结果'];
//【限制】只能上传一个图片文件的：
export const ResultDiagram=
    React.forwardRef((
        { children, show ,alone=true,redId,nestMd, repId,label}:InternalItemProps,  ref
    ) => {
        const {modified,setModified,} =React.useContext(EditStorageContext) as any;
        const [getInpFilter] = useMeasureInpFilter(null, itemA测点位置, );
        const {inp, setInp,onSure} = useInputControlSure({ ref,redId,nestMd });
        const onFinish = React.useCallback(async(upfile: any, del:boolean) => {
            onSure({...inp, '_FILE_部位': upfile});
            !modified && setModified(true);
        }, [inp, modified,onSure,setModified]);
        const [uploadDom]=useUppyUpload({ repId:repId!,
                  maxFile:1, onFinish, storeObj: inp?._FILE_部位
        });
        return (
            <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show} redId={redId} nestMd={nestMd}
                                 alone={alone}  label={label!}>
                <InputLine label='检查部位示意图：'>
                    <BlobInputList value={inp?.示图说明 || ''} rows={4} datalist={示图说明选}
                                   onListChange={v => setInp({...inp, 示图说明: v || undefined}) } />
                </InputLine>
                测厚点部位示意图：
                {uploadDom}
                检测结果:
                <TextArea  value={inp?.检测结果 ||''} rows={3}
                           onChange={e => setInp({ ...inp, 检测结果: e.currentTarget.value||undefined}) } />
                {children}
            </InspectRecordLayout>
        );
    } );


const EntranceSetup =
    React.forwardRef((
        {children, show, alone = true, repId, verId, rep}: InternalItemProps, ref
    ) => {
        const atPrint = useMedia('print');
        const toast = useToast();
        const doCheckNames = React.useCallback((verId: string) => {
            const result = assertNamesUnique([{value: rep?.tzFields},
                {value: config测量仪, type:'esnt'},
                {value:[ ...itemA测点位置, ]},
            ]);
            toast({title: "完成！", subtitle: result ? "没发现冲突" : "测试开关没开", intent: "success"});
        }, [rep,toast]);
        const {storage, setStorage} =React.useContext(EditStorageContext) as any;
        const getInpFilter = React.useCallback((par: any) => {
            const {_tblFixed, } =par||{};
            return {_tblFixed, };
        }, []);
        const {inp, setInp} = useItemInputControl({ref});
        if (atPrint) return null;
        else return (
            <InspectRecordLayout inp={inp} setInp={setInp} getInpFilter={getInpFilter} show={show}
                                 alone={alone} label={'初始化本报告，默认值配置等'}>
                {process.env.REACT_APP_TEST==='true' && <><div>
                    <Text variant="h5">构建开发模板时的工具：校验模板的存储name冲突；</Text>
                    <Button intent='primary' onPress={() => doCheckNames(verId!)}>校验模板name唯一性</Button>
                    <Text variant="h5">设置待测试表格的各列宽度：</Text>
                    <TextArea value={storage?._tblFixed || ''} rows={2} onChange={e =>{
                        JSON.parse(e.currentTarget.value??'[]');
                        setStorage({ ...storage, _tblFixed: e.currentTarget.value || undefined}); }}/>
                </div></>
                }
                <hr/>
            </InspectRecordLayout>
        );
    });

const defvcbFunc = (par: any) => {
    return  par;
};

const recordPrintList = [
    createItem('Entrance', <EntranceSetup/>),
    createItem('Instrument', <TestMethod config={config测量仪}  defValCb={defvcbFunc} label={'内窥镜检查报告-概况'}/>),
    createItem('ResultDiagram', <ResultDiagram label={'内窥镜检查-检查部位示意图'}/>),
] as EditorAreaConfig[];
